<template>
  <!-- 外层div高度固定，class 用于样式穿透 -->
  <vue-ueditor-wrap
    v-model="content"
    :editor-id="editor"
    :config="editorConfig"
    :editorDependencies="['ueditor.config.js', 'ueditor.all.js']"
    @update:modelValue="handleEditorUpdate"
    @ready="onEditorReady"
  />
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { ref, watch } from 'vue';
const props = defineProps({
  modelValue: {
    type: String,
    default: '123',
  },
});

const content = ref(props.modelValue);
const emit = defineEmits(['update:modelValue', 'editorUpdate']);
const userStore = useUserStore();

// 编辑器ID和样式
const editor = ref('editor-' + Date.now());
// const editorStyle = ref({ height: '600px' });

// 新增：定义editor实例引用
const editorInstance = ref<any>(null);

// 编辑器配置
const editorConfig = {
  serverUrl: '/api/manage/editor/server',
  serverHeaders: {
    JWT: 'Bearer ' + userStore.token,
  },
  serverResponsePrepare: function (res: any) {
    if (res.code === 200) {
      return res.data;
    }
  },
  UEDITOR_HOME_URL: '/static/UEditorPlus/dist-min/',
  UEDITOR_CORS_URL: '/static/UEditorPlus/dist-min/',
  // 初始化高度
  initialFrameHeight: 600,
  // 自动高度
  autoHeightEnabled: false,
  // 自动浮动
  autoFloatEnabled: false,
  // 元素路径
  elementPathEnabled: false,
  // 自定义样式，限制视频最大宽度
  inintStyle: {
    video: {
      defaultWidth: '100%',
      defaultHeight: 'auto',
      maxWidth: '400px',
      minWidth: '300px',
    },
  },
};

// 监听外部传入的内容变化，更新编辑器内容
watch(
  () => props.modelValue,
  (val) => {
    if (val !== content.value) content.value = val;
  },
);

// 监听编辑器内容变化，向外同步
watch(content, (val) => {
  emit('update:modelValue', val);
  // 同时触发 editorUpdate 事件，供父组件监听
  emit('editorUpdate', val);
});

// 新增：ready事件回调，获取editor实例
const onEditorReady = (editor: any) => {
  // 保存editor实例
  editorInstance.value = editor;
  // 监听afterExecCommand事件
  editor.addListener('afterExecCommand', function (type: any, cmd: any) {
    // 判断命令类型
    if (cmd === 'insertimage' || cmd === 'insertvideo' || cmd === 'insertHtml') {
      // 获取当前内容，查找新插入的图片/视频URL
      const content = editor.getContent();
      // 七牛云域名
      const domain = 'oss.qinniu.web.ai-yaoteng.slovej.icu';
      // 通过正则提取图片和视频URL
      const imgUrls = Array.from(content.matchAll(/<img [^>]*src=["']([^"']+)["']/g)).map((m: any) => m[1]);
      // 匹配视频（video/iframe/embed）
      const videoUrls = [
        ...Array.from(content.matchAll(/<video [^>]*src=["']([^"']+)["']/g)).map((m: any) => m[1]),
        ...Array.from(content.matchAll(/<iframe [^>]*src=["']([^"']+)["']/g)).map((m: any) => m[1]),
        ...Array.from(content.matchAll(/<embed [^>]*src=["']([^"']+)["']/g)).map((m: any) => m[1]),
      ];
      // 合并所有URL
      const allUrls = [...imgUrls, ...videoUrls];
      // 遍历URL，向后端发起请求
      allUrls.forEach(async (url: string) => {
        if ((url.startsWith('http://') || url.startsWith('https://')) && !url.includes(domain)) {
          // 创建formData对象
          const formData = new FormData();
          formData.append('source[]', url);
          // 发送请求，上传图片/视频
          const catchUrl = '/api/manage/editor/server?action=catch';
          await fetch(catchUrl, {
            method: 'POST',
            headers: {
              Authorization: userStore.token,
            },
            body: formData,
          });
        }
      });
    }
  });
};

// 编辑器内容更新
const handleEditorUpdate = (newContent: string) => {
  content.value = newContent;
};
</script>

<style></style>
